package net.begincode.SSO.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.begincode.SSO.bean.SsoUser;
import net.begincode.SSO.bean.Url;
import net.begincode.SSO.exception.UserException;
import net.begincode.SSO.service.UserService;

/**
 * 控制层
 * @author 遗忘
 * @date 2017.4.17
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService service;

	private Logger logger = LoggerFactory.getLogger(UserService.class);
	
	//用户注册
	@RequestMapping("/regist")
	public void regist(SsoUser user,HttpServletRequest request) {
		try {
			int state =  service.addUser(user);
			if(state==2){
				addTicket(request);
			}
		} catch (UserException e) {
			logger.warn("用户注册失败");
			
		}
	}
	
	//用户登录
	@RequestMapping("/login")
	public void login(SsoUser user,HttpServletResponse response,HttpServletRequest request) throws IOException{
		PrintWriter out = response.getWriter();
		try {
			service.login(user);
			addTicket(request);
			out.print("success");
			out.close();
		} catch (UserException e) {
			logger.warn("用户登录失败");
			out.print(e.getMessage());
			out.close();
		}
	}
	
	//添加cookie凭证  向redis中插入数据
	public void addTicket(HttpServletRequest request){
		String ticketCode = service.intoRedis();
		HttpSession session = request.getSession();
		session.setAttribute("ticket", ticketCode);
		session.setMaxInactiveInterval(30*60);
	}
	
	//提供给client的接口，验证登录状态
	@RequestMapping("/verify")
	public @ResponseBody String verify(Url url){
		if(service.verifyLoginState(url)){
			return "true";
		}else{
			return "false";
		}
		
	}
	
}
